# -*- encoding:utf-8 -*-
from demo import app
from demo.utils.funs import *
from . import render_template, route
from demo.models.account import Account
from demo.models.role import Role
from flask import g, request, redirect, url_for, flash

@route('/account/list')
@login_required
@check_access
def account_list():

    page = get_params('p', default=1, type=int)
    size = 30
    condition = {}
    account_obj = Account()
    for k in account_obj.cols:
        v = request.args.get(k)
        if v:
            condition[k] = [v, '=']

    data, page = account_obj.find_pageble(condition, page, size)
    roles = Role().find_all()
    return render_template('/account/list.html', list=data, page=page, req=request.args, roles=roles)



@route('/account/edit', methods=['GET', 'POST'])
@login_required
@check_access
def account_edit():

    id = get_params('id', default=None)

    account_obj = Account()
    roles = Role().find_all()
    if request.method == 'GET':
        # to new
        if not id:
            return render_template('/account/edit.html', account={}, req=request.args, roles=roles)

        # to edit
        data = account_obj.find(id)
        return render_template('/account/edit.html', account=data, req=request.args, roles=roles)

    # save
    try:
        nick_name = get_params('nick_name', required='缺少昵称参数')
        mobile = get_params('mobile', required='缺少手机号参数')
        passwd = get_params('passwd')
        passwd_confirm = get_params('passwd_confirm')
        name = get_params('name', required='缺少用户名参数')
        role_id = get_params('role_id')
    except Exception as e:
        return show_error(str(e))

    if passwd != passwd_confirm:
        return show_error('两次密码输入不一致')

    data = {"nick_name": nick_name, "mobile": mobile, "name": name, "role_id": role_id}
    if passwd:
        data['passwd'] = to_md5(passwd)

    if id:
        res = account_obj.save(data, id)
        if res:
            flash('保存成功')
    else:
        if not passwd:
            return show_error('请输入密码')
        res = account_obj.save(data)
        if not res:
            return show_error('用户已存在')
        else:
            flash('保存成功')

    return redirect(request.headers.get('referer'))



@route('/account/del', methods=['POST'])
@login_required
@check_access
def account_del():

    id = get_params('id', required='缺少必要参数')

    account_obj = Account()
    if account_obj.delete(id):
        flash('删除成功')
    else:
        return show_error('删除失败，请联系管理员')
    return redirect(request.headers.get('referer'))

